package fileEncryption;
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;
import java.io.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.*;
import javax.crypto.spec.*;

/**
 * 文件加密
 * @author Administrator
 *
 */
public class FileEncryption extends Frame implements ActionListener {
	JFrame frame = new JFrame("文件加密");

	TextField tf1 = new TextField();

	TextField tf2 = new TextField();

	TextField tf3 = new TextField();

	Label lb1 = new Label("输入密码(8位)");

	Label lb2 = new Label("再次输入密码");

	Button button2 = new Button("文件");

	Button button3 = new Button("加密");

	Button button4 = new Button("解密");

	File file;

	public FileEncryption() {
		frame.setVisible(true);
		frame.setSize(400, 300);
		frame.add(tf1);
		tf1.setBounds(50, 60, 200, 20);
		frame.add(button2);
		button2.setBounds(300, 50, 60, 30);
		frame.add(lb1);
		lb1.setBounds(50, 90, 100, 20);
		frame.add(tf2);
		tf2.setEchoChar('*');
		frame.add(lb2);
		lb2.setBounds(50, 130, 100, 20);
		tf3.setBounds(50, 160, 200, 20);
		frame.add(tf3);
		tf3.setEchoChar('*');
		tf2.setBounds(50, 110, 200, 20);
		frame.add(button3);
		button3.setBounds(60, 200, 40, 30);
		frame.add(button4);
		button4.setBounds(150, 200, 40, 30);
		button2.addActionListener(this);
		button3.addActionListener(this);
		button4.addActionListener(this);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 用户界面设计
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileEncryption J = new FileEncryption();
	}

	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == button2)// 选择文件
		{
			JFileChooser jfc = new JFileChooser();// 文件选择对话框
			jfc.showOpenDialog(frame);
			file = jfc.getSelectedFile();// 返回所选文件
			tf1.setText(jfc.getSelectedFile().getPath());// 显示选择文件
		}
		if (e.getSource() == button3) {
			String str = tf1.getText();
			
			 if(tf2.getText().length()!=8)//密码长度是否为8，若不为8，提示错误
			    JOptionPane.showMessageDialog(null,"密码为8位！",
			    "alert",JOptionPane.ERROR_MESSAGE);
			 else if (!tf2.getText().equals(tf3.getText()))// 两次密码是否匹配
					JOptionPane.showMessageDialog(null, "两次密码不匹配！", "alert",
							JOptionPane.ERROR_MESSAGE);
			else {
				try {
					encrypt(file, str);
				} catch (Exception e1) {
						// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		if (e.getSource() == button4)// 解密
		{
				String str1 = tf1.getText();
				// 文件是否为已加密文件，若不是则提示错误
				if (!file.getAbsolutePath().substring(
						file.getAbsolutePath().length() - 5).equals(".tdes"))
					JOptionPane.showMessageDialog(null, "不是已加密文件！", "alert",
							JOptionPane.ERROR_MESSAGE);
				else if (tf2.getText().length() != 8)// 密码是否为8位
					JOptionPane.showMessageDialog(null, "密码为8位！", "alert",
							JOptionPane.ERROR_MESSAGE);
				else if (!tf2.getText().equals(tf3.getText()))// 两次密码是否匹配
					JOptionPane.showMessageDialog(null, "两次密码不匹配！", "alert",
							JOptionPane.ERROR_MESSAGE);
				else {
					try {
						decrypt(file.getAbsoluteFile(), str1);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		}
	// 加密函数
	public void encrypt(File f, String s) throws Exception {
		byte btin[] = new byte[8];
		for (int i = 0; i < 8; i++)
			btin[i] = (byte) s.charAt(i);// 将密码转化为字符数组
		FileInputStream input = new FileInputStream(f);
		byte[] binput = new byte[(int) input.available()];
		for (int i = 0; i < input.available(); i++)
			binput[i] = (byte) input.read();// 将文件读到字符数组中
		byte byteout[] = encryptbyDes(binput, btin);// 文件加密
		String fileOut = f.getPath() + ".tdes";// 创建新文件
		FileOutputStream output = new FileOutputStream(fileOut);
		for (int j = 0; j < byteout.length; j++)
			output.write((int) byteout[j]);
		input.close();
		output.close();
		f.delete();// 删除原文件
		JOptionPane.showMessageDialog(this, "加密成功！", "提示",
				JOptionPane.OK_OPTION);
	}

	public void decrypt(File f, String s) throws Exception {
		byte btin[] = new byte[8];
		for (int i = 0; i < 8; i++)
			btin[i] = (byte) s.charAt(i);// 将密码转换成字节数组
		FileInputStream input = new FileInputStream(f);
		byte[] binput = new byte[(int) f.length()];
		for (int i = 0; i < f.length(); i++)
			binput[i] = (byte) input.read();// 将文件读到字节数组中
		byte fileout[] = decryptbyDes(binput, btin);// 解密文件
		String fileOut = f.getPath().substring(0, f.getPath().length() - 5);
		FileOutputStream output = new FileOutputStream(fileOut);
		output.write(fileout);
		output.flush();
		input.close();
		output.close();
		f.delete();// 删除原文件
		JOptionPane.showMessageDialog(this, "解密成功！", "提示",
				JOptionPane.OK_OPTION);
	}
//文件加密
	public byte[] encryptbyDes(byte[] b1, byte[] b2) throws Exception {
		DESKeySpec desKS = new DESKeySpec(b2);//创建一个 DESKeySpec 对象，使用b2作为DES密钥的密钥内容。
		SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
		SecretKey sk = skf.generateSecret(desKS);//使用DES生成 SecretKey 对象。
		Cipher cip = Cipher.getInstance("DES");//创建Cipher对象
		cip.init(Cipher.ENCRYPT_MODE, sk);//加密
		return cip.doFinal(b1);//返回加密后的字节数组
	}
//文件解密
	public byte[] decryptbyDes(byte[] bytE, byte[] bytKey) throws Exception {
		DESKeySpec desKS = new DESKeySpec(bytKey);//创建一个 DESKeySpec 对象，使用b2作为DES密钥的密钥内容。
		SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
		SecretKey sk = skf.generateSecret(desKS);//使用DES生成 SecretKey 对象。
		Cipher cip = Cipher.getInstance("DES");//创建Cipher对象
		cip.init(Cipher.DECRYPT_MODE, sk);//解密
		return cip.doFinal(bytE);//返回解密后的字节数组

	}

}
